
/**
 * Created with IntelliJ IDEA.
 * Description:
 * 采用前序遍历的方式，将二叉树转化为一个由括号和整数组成的字符串，
 * 返回构造出的字符串。
 * 空节点使用一对空括号对 "()" 表示，转化后需要省略所有不影响字符串与原始二叉树之间的一对一映射关系的空括号对。
 * User: xwl
 * Date: 2023-05-22
 * Time: 21:40
 */

class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode() {}
     TreeNode(int val) { this.val = val; }
     TreeNode(int val, TreeNode left, TreeNode right) {
         this.val = val;
         this.left = left;
         this.right = right;
     }
}
class Solution {
    public String tree2str(TreeNode root) {
        if (root == null) {
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();
        tree2strChild(root,stringBuilder);

        return stringBuilder.toString();
    }

    public void tree2strChild(TreeNode root, StringBuilder stringBuilder) {
        if (root == null) {
            return;
        }

        stringBuilder.append(root.val);
        // 讨论节点的左子树情况
        if (root.left != null) {
            stringBuilder.append("(");
            tree2strChild(root.left, stringBuilder);
            stringBuilder.append(")");
        }else {
            if (root.right != null) {
                stringBuilder.append("()");
            }else {
                return;
            }
        }
        // 讨论节点的右子树情况
        if (root.right == null) {
            return;
        }else {
            stringBuilder.append("(");
            tree2strChild(root.right, stringBuilder);
            stringBuilder.append(")");
        }
    }
}